package com.example.chapter3.homework;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.example.chapter3.homework.PageFragment.mPageFrament1;
import com.example.chapter3.homework.PageFragment.mPageFrament2;
import com.example.chapter3.homework.PageFragment.mPageFrament3;

import java.util.Vector;

// 用来做页面绑定，由于Vector的一些性质，本页面支持十个tab page，可以使用map改进
public class PageAdapter extends FragmentPagerAdapter {

    private int amount;
    private Vector<Fragment> fragmentVector=new Vector<>(10);

    public PageAdapter(FragmentManager fragmentManager,int amount){
        super(fragmentManager);
        for(int i=0;i<amount;++i){
            fragmentVector.add(null);
        }
        this.amount=amount;
    }

    // 返回已有或新创建的fragment
    @Override
    public Fragment getItem(int i) {
        return createFragment(i);
    }

    @Override
    public int getCount() {
        return amount;
    }

    private Fragment createFragment(int position){
        Fragment fragment=fragmentVector.get(position);
        // position应与tab的顺序保持一致
        if(null==fragment){
            switch (position){
                case 2:
                    fragment=new mPageFrament1();
                    break;
                case 1:
                    fragment=new mPageFrament2();
                    break;
                case 0:
                    fragment=new PlaceholderFragment();
                    break;
                case 3:
                    fragment=new mPageFrament3();
                    break;
                    default:break;
            }
            fragmentVector.add(position,fragment);

        }
        return fragment;
    }

}
